<?php

abstract class Page_Rewrite {

	/************ PAGE REWRITING *********/
	
	private static $rewrites;
	private static $unwrites;

	protected static function Load_Rewrites(){
		if(!isset(self::$rewrites) || !isset(self::$unwrites)){
			$result = Database::getInstance()->query('SELECT * from `pages` WHERE `site` = %u', Site::getInstance()->getID());
			Page_Rewrite::$rewrites = array();
			while($rewrite =$result->fetch_assoc()){
				self::$rewrites[$rewrite['name']] = $rewrite['location'];
				self::$unwrites[$rewrite['location']] = $rewrite['name'];
			}
		}
	}


	public static function Rewrite($name){
		self::Load_Rewrites();
		$name = trim($name,'/');
		$page = explode('/',$name);

		$possibles = array();
		$base = '';

		foreach($page as $p){
			$possible = $base . $p;
			$base .= $p . '/';
			$rest = trim(substr($name,strlen($possible)),'/');
			$possibles[$possible] = $rest;
		}

		$possibles = array_reverse($possibles);

		$pages = array();

		foreach($possibles as $k => $v){
			if(isset(self::$rewrites[$k])){
				if(trim($k . '/' . $v, '/') != ''){
					$pages[trim(trim(self::$rewrites[$k],'/') . '/' . $v, '/')] = true;
				}
			} else {
				if(trim($k . '/' . $v, '/') != ''){
					$pages[trim($k . '/' . $v, '/')] = false;
				}
			}
		}

		return $pages;
	}

	public static function Unwrite($name){
		self::Load_Rewrites();

		$name = trim($name,'/');
		$shortest = $name;
		$page = explode('/', $name);
		$possibles = array();
		$base = '';

		foreach($page as $p){
			$possible = $base . $p;
			$base .= $p . '/';
			$rest = trim(substr($name,strlen($possible)),'/');
			$possibles[$possible] = $rest;
		}

		$possibles = array_reverse($possibles);
		
		foreach($possibles as $k => $v){
			if(isset(Page_Rewrite::$unwrites[$k])){
				if(trim($k . '/' . $v, '/') != ''){
					$addy = trim(trim(self::$unwrites[$k],'/') . '/' . $v, '/');
					if(strlen($addy) < strlen($shortest)){
						$shortest = $addy;
					}
				}
			}
		}

		return $shortest;
	}

}
